﻿using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Io.Elegant;
using System.Net;
using System.Net.Sockets;

namespace Elio;

public static class Utils
{
    //P2 <=> protobuf to
    public static string P2String(this Any any) => any.Unpack<StringValue>().Value;
    public static int P2Int(this Any any) => any.Unpack<Int32Value>().Value;
    public static long P2Long(this Any any) => any.Unpack<Int64Value>().Value;
    public static bool P2Bool(this Any any) => any.Unpack<BoolValue>().Value;
    public static double P2Double(this Any any) => any.Unpack<FloatValue>().Value;
    public static Interaction P2Interaction(this Any any) => any.Unpack<Interaction>();

    public static Any ToAny(this string str) => Any.Pack(new StringValue { Value = str });
    public static Any ToAny(this int num) => Any.Pack(new Int32Value { Value = num });
    public static Any ToAny(this bool b) => Any.Pack(new BoolValue { Value = b });
    public static Any ToAny(this double d) => Any.Pack(new FloatValue { Value = (float)d });
    public static Any ToAny(this byte[] bytes) => Any.Pack(new BytesValue { Value = ByteString.CopyFrom(bytes) });

    public static string GetIpAddress()
    {
        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress? ipAddress = host
            .AddressList
            .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

        return ipAddress?.ToString() ?? string.Empty;
    }

    public static string GetClientId()
    {
        const string keyId = "ClientID";

        if (Preferences.Default.ContainsKey(keyId))
            return Preferences.Default.Get(keyId, string.Empty);

        string clientId = Guid.NewGuid().ToString();
        Preferences.Default.Set(keyId, clientId);
        return clientId;
    }

    public static string GetPlatform() =>
        DeviceInfo.Current.Platform.ToString();
}
